/* global VueRouter, Vue */

import NProgress from 'nprogress'
import { WEB_TITLE_PREFIX } from 'common/consts'
import global from 'common/globals'
import { isEmpty } from 'utils/ui-utils'

import baseRoutes from './base'
import userRoutes from './users'
import courseRoutes from './course'

const routes = [
  ...baseRoutes,
  ...userRoutes,
  ...courseRoutes
]
const router = new VueRouter({ routes })

router.beforeEach((to, from, next) => {
  document.body.scrollTop = 0
  const prefix = global.store.state && global.store.state.appPrefix
  const scrollEl = document.body.querySelector(`.${prefix}-my-app .${prefix}-my-app-wrap`)
  if (scrollEl) {
    scrollEl.scrollTop = 0
  }
  NProgress.start();
  const currentMenuItem = {}

  const store = Vue.prototype.$globalStore
  const sysname = store.state.user.userInfo && store.state.user.userInfo.companySysName || WEB_TITLE_PREFIX

  if (currentMenuItem && currentMenuItem.text) {
    document.title = `${currentMenuItem.text} | ${sysname}`
  } else if (to.meta.title) {
    document.title = `${to.meta.title} | ${sysname}`
  }
  if (from.params && !isEmpty(from.params)) {
    global.store.state.pageStatusInfo[from.name] = from.path
  }
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
